<template>
	<view>

		<uni-popup ref="popup" type="bottom" background-color="#fff" @change="bindClose">
			<view class="popup-content" style="height:630rpx">
				<view class="downs" @click="bindClose($event, 1)">
					<view class="downs-btn"></view>
					<view class="">{{ ['选择日期', '选择周', '选择月份'][dateCurr - 1] }}</view>
				</view>
				<picker-view class="picker-view" :indicator-style="indicatorStyle" :value="selectValue"
					@change="bindChange">
					<picker-view-column :style="dateCurr === 2 ? 'flex:0 0 200rpx;' : ''">
						<view class="item" v-for="(item, index) in years" :key="index">{{ item }}年</view>
					</picker-view-column>
					<picker-view-column v-if="dateCurr === 1 || dateCurr === 3">
						<view class="item " v-for="(item, index) in months" :key="index">
							{{ item }}月
							<text style="right: 27%;"
								v-if="nowYear == year && item == monthsCur && dateCurr === 3">本月</text>
						</view>
					</picker-view-column>
					<picker-view-column v-if="dateCurr === 1">
						<view class="item" v-for="(item, index) in days" :key="index">{{ item }}日
							<text style="right: 12%;" v-if="item == daysCur">今日</text>
						</view>
					</picker-view-column>
					<picker-view-column v-if="dateCurr === 2">
						<view class="item" v-for="(item, index) in weekList" :key="index">{{ item.week }}({{ item.date }})
							<text style="right: 0;" v-if="item.year==nowYear&& item.value == weekCur">本周</text>
						</view>
					</picker-view-column>
				</picker-view>
				<view class="bottoms">
					<view class="reSet" @click="bindClose($event, 1)">取消</view>
					<view class="submit" @click="submitDate">确认</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
import dayjs from 'dayjs';
function getWeeks(now) {
	if (now) {
		var today = new Date(now);
		var firstday = new Date();  // 该年的第一天
		var year = now.slice(0, now.indexOf('-'));
		firstday.setYear(year);
		firstday.setMonth(0);
		firstday.setDate(1);  // 设置成这年的一月一号
		var timing = today - firstday;
		var days = Math.ceil(timing / (24 * 60 * 60 * 1000));  // 距离第一天共有多少天
		days += firstday.getDay() + 1;  // 假如今年一月一号是星期三，第一周就已经过去了三天，加上西方认为星期天是一周的第一天
		var weeks = Math.ceil(days / 7);  // 获得周数
		// console.log(today, firstday, days, weeks);
		return weeks;
	}
}
export default {
	name: 'weekYearDate',
	data() {
		return {
			monthsCur: dayjs().format('MM'),
			daysCur: dayjs().format('DD'),
			weekCur: getWeeks(dayjs().format('YYYY-MM-DD')) ,
			nowYear: new Date().getFullYear(),
			years: [],
			year: new Date().getFullYear(),
			months: [],
			month: '',
			days: [],
			day: '',
			weekList: [],// 年周数据
			weekIndex: null,// 周下标
			selectDate: null,// 日期选择数据
			selectValue: [],// 日期选择
			indicatorStyle: `color: #0091ff;height: ${Math.round(uni.getSystemInfoSync().screenWidth / (950 / 100))}px;`
		};
	},
	watch: {
		showState(val) {
			if (val) {
				// this.$refs.popup.open()
			} else {
				// this.$refs.popup.close()
			}
			if (this.dateCurr === 2) {
				let nums = getWeeks(dayjs().format('YYYY-MM-DD')) - 1;
				this.selectValue = [9999, nums, 1];
			} else {
				this.selectValue = [Number(dayjs().format('YYYY')), dayjs().format('MM') - 1, dayjs().format('DD') - 1];
			}
		}
	},
	props: {
		dateCurr: {// 1年月日 2年周 3年月
			type: Number,
			default: 1
		},
		showState: {
			type: Boolean,
			default: false,
		},
	},

	mounted() {
		this.getTimes();
		this.setWeekList(dayjs().format('YYYY'));
	},
	methods: {
		setWeekList(year) {
			let arrWeek = this.getAllWeekRange(year) || [];
			let arr = [];
			for (let i = 1; i <= arrWeek.length; i++) {
				// console.log("arrarr",i,arrWeek[i-1])
				if (arrWeek[i - 1].value <= getWeeks(dayjs().format('YYYY-MM-DD')) || year < this.nowYear) {
					arr.push({ ...arrWeek[i - 1] });
				}
				// arr.push({ ...arrWeek[i - 1] })
			}
			// console.log('week',arr,arrWeek,this.weekCur)
			this.weekList = arr;
		},
		// 关闭
		bindClose(e, type) {
			if (!e.show) {
				this.$emit('bindClose', false);
			}
			if (type === 1) {
				this.$emit('bindClose', false);
			}
		},
		// 日期选择
		bindChange(e) {
			const val = e.detail.value;
			let year = this.years[val[0]];
			this.setMonth(year);
			let month = this.months[val[1]];
			if (this.dateCurr === 1) {// 日选择
				this.days = [];
				let day = val[2] + 1;
				let monthDays = this.solarDays(year, month);// 获取每月日数
				const curDays = new Date().getDate();

				if (month == new Date().getMonth() + 1 && year == this.nowYear) {// 当月获取当前天数
					for (let i = 1; i <= curDays; i++) {
						this.days.push(i);
					}
					this.daysCur = dayjs().format('DD');
				} else {
					for (let i = 1; i <= monthDays; i++) {
						this.days.push(i);
					}
					this.daysCur = 32;
				}

				this.selectDate = year + '/' + (month < 10 ? '0' + month : month) + '/' + (day < 10 ? '0' + day : day);
			}
			if (year != this.year) {
				this.setWeekList(year);
				this.year = year;
			}
			
			if (this.dateCurr === 2) {// 周选择
				this.weekIndex = val[1]; // 周下标
				// this.weekList = this.getAllWeekRange(year)
			}
			if (this.dateCurr === 3) {// 月选择
				this.selectDate = year + '/' + (month < 10 ? '0' + month : month);
			}
			// console.log('year',year,this.months)
		},
		// 年月的天数
		solarDays: function (y, m) {
			let solarMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
			if (m > 12 || m < 1) {
				return -1; 
			} // 若参数错误 返回-1
			var ms = m - 1;
			if (ms == 1) { // 2月份的闰平规律测算后确认返回28或29
				return (((y % 4 == 0) && (y % 100 != 0) || (y % 400 == 0)) ? 29 : 28);
			} else {
				return (solarMonth[ms]);
			}
		},
		// 初始日期
		getTimes() {
			const date = new Date();
			const years = [];
			const year = date.getFullYear();
			const month = new Date().getMonth() + 1;

			const days = [];
			const day = date.getDate();
			let yearsCount = date.getFullYear();

			for (let i = 2022; i <= yearsCount; i++) {
				this.years.push(i);
			}
			this.setMonth(year);

			// let monthDays = this.solarDays(year,month)//每月日数
			for (let c = 1; c <= day; c++) {
				this.days.push(c);
			}
			setTimeout(() => {
				this.selectValue = [year - 1, month - 1, day - 1];
				// this.indicatorStyle = "color: #0091FF;"
			}, 1000);
		},

		setMonth(year) {
			const nowYear = new Date().getFullYear();
			let months = [];
			let month = 12;// 
			if (year == nowYear) {
				month = new Date().getMonth() + 1;
			}
			for (let j = 1; j <= month; j++) {
				months.push(j);
			}
			this.months = months;
		},

		// 通过年获取 本年周数  year 年
		getWeekNum(year) {
			const firstDay = (new Date(parseInt(year), 0, 1)).getDay(), // 设置该年1.1星期
				endDay = (new Date(parseInt(year), 11, 31)).getDay(); // 设置该年12.31星期

			// 该年最大周次.1.1.在周一到周四,则为该年第一周,否则为上年最后一周.
			const flag = ((firstDay >= 1 && firstDay <= 4) && (endDay == 0 || endDay == 4 || endDay == 5 || endDay ==
				6));
			// 1.1.和12.31.都在本年,则该年有53周,否则52周
			const maxWeek = flag ? 53 : 52;
			return maxWeek;
		},
		// 通过年份、周数获取日期范围   year 年   weeks 周  getWeekRange(2019,12))--> 2019-03-18~2019-03-24
		// 参数:type 日期是否补零 默认日期补零
		getWeekRange(year, weekNum, type = 1) {
			const yearStart = new Date(parseInt(year), 0, 1), // 设置该年1.1.
				firstDay = yearStart.getDay(); // 星期
			// 对1.1.所在周的前后几天特殊处理.
			const other = (firstDay >= 0 && firstDay <= 4) ? firstDay - 1 : firstDay - 8;

			// 时间调整,得出要计算周的起/始时间.
			// 考虑距离当年1.1.的总天数
			let days = (parseInt(weekNum, 10) - 1) * 7 - other;
			// 一天时间的毫秒数
			let oneDay = 24 * 60 * 60 * 1000;

			// 当前周 第一天 离1/1/70的毫秒数.
			let dateInMs = oneDay * days + yearStart.getTime();
			// 日期调整(设置1/1/70至今的毫秒数)
			const weekStart = new Date(dateInMs);

			// 当前所选周最后一天处理,同上.
			let dateInMsE = oneDay * 6 + dateInMs;
			const weekEnd = new Date(dateInMsE);

			// 月和日的处理,一位变两位,如:1->01.
			let month = weekStart.getMonth() + 1;
			let day = weekStart.getDate();

			let monthE = weekEnd.getMonth() + 1;
			let dayE = weekEnd.getDate();

			if (type === 1) {
				month = (month < 10) ? '0' + month : month;
				day = (day < 10) ? '0' + day : day;
				monthE = (monthE < 10) ? '0' + monthE : monthE;
				dayE = (dayE < 10) ? '0' + dayE : dayE;
			}

			// return (weekStart.getFullYear() + "-" + month + "-" + day) + "~" + (weekEnd.getFullYear() + "-" + monthE + "-" + dayE)
			return (month + '月' + '' + day + '日') + '-' + (monthE + '月' + '' + dayE + '日');
			// return (month + day) + "-" + (monthE + dayE)
		},
		// 根据具体日期，获取当天所在周的周数
		getYearWeek(dateString) {
			var da = dateString; // 日期格式2015-12-30
			// 当前日期
			var date1 = new Date(da.substring(0, 4), parseInt(da.substring(5, 7)) - 1, da.substring(8, 10));
			// 1月1号
			var date2 = new Date(da.substring(0, 4), 0, 1);
			// 获取1月1号星期（以周一为第一天，0周一~6周日）
			var dateWeekNum = date2.getDay() - 1;
			if (dateWeekNum < 0) {
				dateWeekNum = 6;
			}
			if (dateWeekNum < 4) {
				// 前移日期
				date2.setDate(date2.getDate() - dateWeekNum);
			} else {
				// 后移日期
				date2.setDate(date2.getDate() + 7 - dateWeekNum);
			}
			var d = Math.round((date1.valueOf() - date2.valueOf()) / 86400000);
			if (d < 0) {
				var date3 = (date1.getFullYear() - 1) + '-12-31';
				return getYearWeek(date3);
			} else {
				// 得到年数周数
				var year = date1.getFullYear();
				var week = Math.ceil((d + 1) / 7);
				return week;
			}
		},

		// 获取每年 所有周的范围
		getAllWeekRange(year) {
			let weekNum = this.getWeekNum(year); 
			let weeks = [];
			for (let index = 1; index <= weekNum; index++) {
				let range = this.getWeekRange(year, index, 1);
				let rangestr = '第' + index + '周';
				weeks.push({
					date: range,
					week: rangestr,
					year: year,
					value: index,
				});
			}
			return weeks;
		},
		// 确认
		submitDate() {
			if (this.dateCurr === 2) {
				let obj = this.weekList.find((item, i) => i === this.weekIndex);
				let arr = obj.date.replace(/['月','日']/g, '/').split('-');

				let str = obj.year + '/' + arr[0].substring(0, 5) + '-' + obj.year + '/' + arr[1].substring(0, 5);
				this.selectDate = str;
			}
			if (this.selectDate) {
				this.$emit('selectChange', this.selectDate);
			}
			this.$refs.popup.close();
		},

	}
};
</script>

<style lang="scss" scoped>
.popup-content {
	display: flex;
	flex-direction: column;
	padding: 30rpx;
	// height: 50px;
	background-color: #fff;
	border-radius: 8rpx 8rpx 0rpx 0rpx;

	.picker-view {
		width: 680rpx;
		height: 500rpx;
		margin-top: 20rpx;
		margin: 0 auto;

		.item {
			height: 100rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			text-align: center;
			position: relative;

			text {
				position: absolute;
				right: 5%;
				margin-top: 10rpx;
				display: inline-block;
				width: 52rpx;
				height: 28rpx;
				background: #f3f6f8;
				border-radius: 4rpx;
				font-size: 20rpx;
				font-weight: 400;
				text-align: center;
				color: #0091ff;
				line-height: 28rpx;
			}
		}

		.item {}

	}

	/deep/.indicatorStyle {
		color: #0091ff;
	}

	.downs {
		width: 100%;

		.downs-btn {
			width: 64rpx;
			height: 10rpx;
			background: #d8d8d8;
			border-radius: 6rpx;
			margin: 0 auto;
		}
	}

	.bottoms {
		display: flex;
		margin-top: 20rpx;

		// width: 710rpx;
		view {
			display: flex;
			flex: 1;
			height: 70rpx;
			justify-content: center;
			align-items: center;
			border-radius: 8rpx;
			font-size: 28rpx;
		}

		.reSet {
			background-color: #f5fbff;
			color: #0091ff;
			margin-right: 10rpx;
		}

		.submit {
			background-color: $theme-color;
			color: #fff;
		}
	}
}
</style>